package com.ssyshop.info.fragment;


import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.graphics.Paint;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.RequiresApi;
import android.support.v4.app.Fragment;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ViewFlipper;

import com.android.volley.RequestQueue;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.NetworkImageView;
import com.android.volley.toolbox.Volley;
import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.BDLocation;
import com.baidu.location.Poi;
import com.google.gson.Gson;
import com.ssyshop.info.R;
import com.ssyshop.info.activity.home.GoodsInfoActivity;
import com.ssyshop.info.activity.location.LoacationActivity;
import com.ssyshop.info.https.OkHttpClientManager;
import com.ssyshop.info.model.Advertising;
import com.ssyshop.info.model.Goods;
import com.ssyshop.info.model.NavigationButton;
import com.ssyshop.info.model.News;
import com.ssyshop.info.service.LocationApplication;
import com.ssyshop.info.service.LocationService;
import com.ssyshop.info.utils.BitmapCache;
import com.ssyshop.info.utils.Config;
import com.ssyshop.info.utils.Tools;
import com.ssyshop.info.view.SelfDialog;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.PermissionListener;
import com.yanzhenjie.permission.Rationale;
import com.yanzhenjie.permission.RationaleListener;
import com.yanzhenjie.permission.SettingService;
import com.zhy.adapter.recyclerview.CommonAdapter;
import com.zhy.adapter.recyclerview.MultiItemTypeAdapter;
import com.zhy.adapter.recyclerview.base.ViewHolder;
import com.zyao89.view.zloading.ZLoadingDialog;
import com.zyao89.view.zloading.Z_TYPE;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import okhttp3.FormBody;
import okhttp3.Response;

/**
 * A simple {@link Fragment} subclass.
 * 首页
 */
public class HomePageFragment extends Fragment implements View.OnClickListener {


    public HomePageFragment() {
        // Required empty public constructor
    }


    ViewPager viewPager;
    //图片数组
    private List<String> list_url = new ArrayList<String>();
    private ArrayList<View> viewlist;

    private NetworkImageView imageView;//是Volley提供的一个自定义View，可直接设置网络图片
    private RequestQueue queue;//利用ImageRequest对象简单、方便地进行网络图片的获取
    private ImageLoader imageLoader;//用于获取或缓存图片
    //点点
    private ViewGroup pointgroup;
    private ImageView[] pointarr;
    private int count = 0;
    private boolean flag = true;
    public Timer mTimer = new Timer();
    /**
     * 消息处理器的应用
     */
    private final int LOAD = 0x002;
    public Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == 0x001) {
                viewPager.setCurrentItem(count);
            }
            if (msg.what == LOAD) {
                if (is_getFlash && is_getNews && is_getAD && is_getNav&&is_getGoods1&&is_getGoods2) {
                    dialog.dismiss();
                    content.setVisibility(View.VISIBLE);
                }
            }
        }

    };

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_home_page, container, false);
        initView(view);
        return view;
    }

    private LinearLayout content;
    private ImageView home_page_dw_btn, home_page_msg_btn;
    private LinearLayout home_page_ed_btn;
    private RecyclerView re_nav, re_spms, re_jfqg;
    private ViewFlipper viewFilpper;
    private ZLoadingDialog dialog;
    private LocationService locationService;
    private boolean is_getFlash = false, is_getGoods1 = false,is_getGoods2 = false, is_getNews = false, is_getAD = false, is_getNav = false;
    private List<News> list_news = new ArrayList<>();
    private List<NavigationButton> list_nav = new ArrayList<>();
    private List<Goods> list_goods = new ArrayList<>();
    private List<Goods> list_goods2 = new ArrayList<>();
    private Advertising ad = null;
    private NetworkImageView home_image;
    private NavAdapter navAdapter;
    private ReMsAdapter reMsAdapter;
    private JfAdapter jfAdapter;

    private void initView(View view) {
        queue = Volley.newRequestQueue(getActivity());
        imageLoader = new ImageLoader(queue, new BitmapCache());
        content = view.findViewById(R.id.content);
        content.setVisibility(View.GONE);
        viewPager = view.findViewById(R.id.viewpager_img);
        pointgroup = view.findViewById(R.id.pointgroup);
        home_page_dw_btn = view.findViewById(R.id.home_page_dw_btn);
        home_page_msg_btn = view.findViewById(R.id.home_page_msg_btn);
        home_page_ed_btn = view.findViewById(R.id.home_page_ed_btn);
        re_nav = view.findViewById(R.id.re_nav);
        viewFilpper = view.findViewById(R.id.viewFilpper);
        home_image = view.findViewById(R.id.home_image);
        re_spms = view.findViewById(R.id.re_spms);
        re_jfqg = view.findViewById(R.id.re_jfqg);
        initData();
        initEvent();
    }

    private void initEvent() {
        viewFilpper.setOnClickListener(this);
        home_page_dw_btn.setOnClickListener(this);
        home_page_msg_btn.setOnClickListener(this);
        viewFilpper.setOnClickListener(this);
        home_image.setOnClickListener(this);
    }

    private void initData() {
        dialog = new ZLoadingDialog(getActivity());
        dialog.setLoadingBuilder(Z_TYPE.STAR_LOADING)//设置类型 STAR_LOADING
                .setLoadingColor(Color.BLACK)//颜色
                .setHintText("Loading...")
                .setHintTextSize(16)// 设置字体大小
                .setHintTextColor(Color.GRAY);// 设置字体颜色
        dialog.show();
        //初始化广告图片
        home_image.setErrorImageResId(R.mipmap.pic_zwt_1);
        home_image.setDefaultImageResId(R.mipmap.pic_zwt_1);

        //获取用户当前位置授权
        showPlace();
        //获取首页显示的一些内容
        GetFlash getFlash = new GetFlash();
        getFlash.execute();
        GetNews getNews = new GetNews();
        getNews.execute();
        GetAD getAD = new GetAD();
        getAD.execute();
        GetNav getNav = new GetNav();
        getNav.execute();
        GetGoodsList1 goodsList_1 = new GetGoodsList1();
        goodsList_1.execute();//限时抢购分类id
        GetGoodsList2 goodsList_2 = new GetGoodsList2();
        goodsList_2.execute("");//积分商品分类id

    }


    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.viewFilpper:
                Toast.makeText(getActivity(), "点击了第" + viewFilpper.getDisplayedChild() + "条新闻", Toast.LENGTH_SHORT).show();
                break;
            case R.id.home_page_dw_btn:
                startActivity(new Intent(getActivity(), LoacationActivity.class));
                break;
            case R.id.home_page_msg_btn:

                break;
            case R.id.home_image:
                Toast.makeText(getActivity(), "点击了" + ad.getAd_name() + "广告", Toast.LENGTH_SHORT).show();
                break;
        }
    }

    private static final int REQUEST_CODE_PERMISSION_LOCATION = 100;
    private static final int REQUEST_CODE_SETTING = 300;
    private SelfDialog selfDialog;

    //获取用户当前位置
    private void showPlace() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {// 适配版本在6.0以上

            if (getActivity().checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED &&
                    getActivity().checkSelfPermission(Manifest.permission.READ_PHONE_STATE) == PackageManager.PERMISSION_GRANTED &&
                    getActivity().checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED &&
                    getActivity().checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {//已经有权限

            } else {
                AndPermission.with(getActivity())
                        .requestCode(REQUEST_CODE_PERMISSION_LOCATION)
                        .permission(Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.READ_PHONE_STATE, Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                        .callback(permissionListener)
                        // rationale作用是：用户拒绝一次权限，再次申请时先征求用户同意，再打开授权对话框；
                        // 这样避免用户勾选不再提示，导致以后无法申请权限。
                        // 你也可以不设置。
                        .rationale(rationaleListener)
                        .start();
            }
        } else {
            //执行操作

        }
    }


    /**
     * 权限申请回调监听。
     */
    private PermissionListener permissionListener = new PermissionListener() {
        // 权限申请成功回调。
        @Override
        public void onSucceed(int requestCode, @NonNull List<String> grantPermissions) {
            if (requestCode == REQUEST_CODE_PERMISSION_LOCATION) {
                // Toast.makeText(LoadActivity.this, "读写内存授权成功", Toast.LENGTH_SHORT).show();
                //执行操作

            }
        }

        // 权限申请失败回调。
        @Override
        public void onFailed(int requestCode, @NonNull List<String> deniedPermissions) {
            if (requestCode == REQUEST_CODE_PERMISSION_LOCATION) {
                // Toast.makeText(LoadActivity.this, "读写内存授权失败", Toast.LENGTH_SHORT).show();
            }

            final SettingService settingHandle = AndPermission.defineSettingDialog(getActivity(), REQUEST_CODE_SETTING);
            selfDialog = new SelfDialog(getActivity(), 0);//默认为0,  1：只有一个按钮
            selfDialog.setTitle("系统提示");
            selfDialog.setMessage("我们需要的一些权限被您拒绝或者系统发生错误申请失败，请您到设置页面手动授权，否则功能无法正常使用！");
            selfDialog.setYesOnclickListener("确定", new SelfDialog.onYesOnclickListener() {
                @Override
                public void onYesClick() {
                    settingHandle.execute();
                }
            });
            selfDialog.setNoOnclickListener("取消", new SelfDialog.onNoOnclickListener() {
                @Override
                public void onNoClick() {
                    selfDialog.dismiss();
                    //settingHandle.cancel();
                    System.exit(0);
                }
            });
            selfDialog.show();

        }
    };

    /**
     * Rationale功能是在用户拒绝一次权限后，再次申请时检测到已经申请过一次该权限了，
     * 允许开发者弹窗说明申请权限的目的，获取用户的同意后再申请权限，避免用户勾选不再提示，导致不能再次申请权限。
     */
    private RationaleListener rationaleListener = new RationaleListener() {
        @Override
        public void showRequestPermissionRationale(int requestCode, Rationale rationale) {
            // 这里用AndPermission默认对话框：
            AndPermission.rationaleDialog(getActivity(), rationale).show();
            // 此对话框可以自定义，调用rationale.resume()就可以继续申请。 rationale.cancel();不继续申请
        }
    };

    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_SETTING) {
            // 你可以在这里检查你需要的权限是否被允许，并做相应的操作。
            if (getActivity().checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {//已经有权限
                //执行操作

            } else {
            }
        }
    }

    /**
     * 查询获取商品列表:商品秒杀
     */
    class GetGoodsList1 extends AsyncTask<String, Void, String> {

        @Override
        protected String doInBackground(String... strings) {

            String url = Config.URL_SERVER + "api.php?app_key=" + Config.APP_KEY + "&method=ssy.goods.list.get&format=json&page_size=5&page=1";
            return OkHttpClientManager.sendGet(url);
        }

        @Override
        protected void onPostExecute(String s) {
            if (s == null) {
                is_getGoods1=true;
                handler.sendEmptyMessage(LOAD);
                return;
            }
            try {
                JSONObject object = new JSONObject(s);
                if (object.getString("result").equals("success")) {
                    JSONObject object1 = object.getJSONObject("info");
                    list_goods = Tools.fromJsonList(object1.getString("list"), Goods.class);
                } else {
                }
                LinearLayoutManager manager = new LinearLayoutManager(getActivity());
                manager.setOrientation(LinearLayoutManager.HORIZONTAL);
                reMsAdapter = new ReMsAdapter(getActivity(), R.layout.item_goods_1, list_goods);
                re_spms.setLayoutManager(manager);
                re_spms.setAdapter(reMsAdapter);
                is_getGoods1=true;
                handler.sendEmptyMessage(LOAD);
            } catch (JSONException e) {
                e.printStackTrace();
            }

        }
    }

    /**
     * 查询获取商品列表：积分抢购
     */
    class GetGoodsList2 extends AsyncTask<String, Void, String> {

        @Override
        protected String doInBackground(String... strings) {
            String url = Config.URL_SERVER + "api.php?app_key=" + Config.APP_KEY + "&method=ssy.goods.list.get&format=json&page_size=5&page=2";
            return OkHttpClientManager.sendGet(url);
        }

        @Override
        protected void onPostExecute(String s) {
            if (s == null) {
                is_getGoods2=true;
                handler.sendEmptyMessage(LOAD);
                return;
            }
            try {
                JSONObject object = new JSONObject(s);
                if (object.getString("result").equals("success")) {
                    JSONObject object1 = object.getJSONObject("info");
                    list_goods2 = Tools.fromJsonList(object1.getString("list"), Goods.class);
                } else {
                }
                LinearLayoutManager manager = new LinearLayoutManager(getActivity());
                manager.setOrientation(LinearLayoutManager.VERTICAL);
                jfAdapter = new JfAdapter(getActivity(), R.layout.item_goods_2, list_goods2);
                re_jfqg.setLayoutManager(manager);
                re_jfqg.setAdapter(jfAdapter);
                is_getGoods2=true;
                handler.sendEmptyMessage(LOAD);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 查询获取幻灯片
     */
    class GetFlash extends AsyncTask<Void, Void, String> {

        @Override
        protected String doInBackground(Void... voids) {
            String url = Config.URL_SERVER + "api.php?app_key=" + Config.APP_KEY + "&method=ssy.base.app.flash";
            return OkHttpClientManager.sendGet(url);
        }

        @Override
        protected void onPostExecute(String s) {
            if (s == null) {
                is_getFlash = true;
                handler.sendEmptyMessage(LOAD);
                return;
            }
            try {
                JSONObject object = new JSONObject(s);
                String result = object.getString("result");
                if (result.equals("success")) {
                    JSONArray array = object.getJSONArray("info");
                    int len = array.length();
                    if (len > 0) {
                        for (int i = 0; i < len; i++) {
                            String pic_url = "";
                            JSONObject object1 = array.getJSONObject(i);
                            pic_url = object1.getString("pic_url");
                            list_url.add(pic_url);
                        }
                    }
                } else {
                }
                is_getFlash = true;
                handler.sendEmptyMessage(LOAD);
                initHDP();
            } catch (JSONException e) {
                e.printStackTrace();
            }

        }
    }

    /**
     * 查询获取新闻
     */
    class GetNews extends AsyncTask<Void, Void, String> {

        @Override
        protected String doInBackground(Void... voids) {
            String url = Config.URL_SERVER + "api.php?app_key=" + Config.APP_KEY + "&method=ssy.base.app.news";
            return OkHttpClientManager.sendGet(url);
        }

        @Override
        protected void onPostExecute(String s) {
            if (s == null) {
                is_getNews = true;
                handler.sendEmptyMessage(LOAD);
                return;
            }
            try {
                JSONObject object = new JSONObject(s);
                if (object.getString("result").equals("success")) {
                    JSONObject object1 = object.getJSONObject("info");
                    JSONArray array = object1.getJSONArray("list");
                    int len = array.length();
                    if (len > 0) {
                        for (int i = 0; i < len; i++) {
                            News news = new News();
                            JSONObject object2 = array.getJSONObject(i);
                            news.setArticle_id(object2.getString("article_id"));
                            news.setCat_id(object2.getString("cat_id"));
                            news.setTitle(object2.getString("title"));
                            news.setContent(object2.getString("content"));
                            news.setAuthor(object2.getString("author"));
                            news.setAuthor_email(object2.getString("author_email"));
                            news.setKeywords(object2.getString("keywords"));
                            news.setArticle_type(object2.getString("article_type"));
                            news.setIs_open(object2.getString("is_open"));
                            news.setAdd_time(object2.getString("add_time"));
                            news.setFile_url(object2.getString("file_url"));
                            news.setOpen_type(object2.getString("open_type"));
                            news.setLink(object2.getString("link"));
                            news.setDescription(object2.getString("description"));
                            list_news.add(news);
                            TextView tv = new TextView(getActivity());
                            tv.setText(news.getTitle());
                            tv.setGravity(Gravity.CENTER_VERTICAL);
                            viewFilpper.addView(tv, i);
                        }
                    }
                } else {

                }
                is_getNews = true;
                handler.sendEmptyMessage(LOAD);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 查询获取广告图片
     */
    class GetAD extends AsyncTask<Void, Void, String> {

        @Override
        protected String doInBackground(Void... voids) {
            String url = Config.URL_SERVER + "api.php?app_key=" + Config.APP_KEY + "&method=ssy.base.app.ad&ad_name=index1";
            return OkHttpClientManager.sendGet(url);
        }

        @Override
        protected void onPostExecute(String s) {
            if (s == null) {
                is_getAD = true;
                handler.sendEmptyMessage(LOAD);
                return;
            }
            try {
                JSONObject object = new JSONObject(s);
                if (object.getString("result").equals("success")) {
                    ad = new Advertising();
                    JSONObject object1 = object.getJSONObject("info");
                    ad.setAd_id(object1.getString("ad_id"));
                    ad.setMedia_type(object1.getString("media_type"));
                    ad.setAd_name(object1.getString("ad_name"));
                    ad.setB_title(object1.getString("b_title"));
                    ad.setS_title(object1.getString("s_title"));
                    ad.setAd_code(object1.getString("ad_code"));
                    ad.setStart_time(object1.getString("start_time"));
                    ad.setEnd_time(object1.getString("end_time"));
                    ad.setClick_count(object1.getString("click_count"));
                    ad.setAd_type(object1.getString("ad_type"));
                    ad.setIs_start(object1.getString("is_start"));
                    ad.setPic_url(object1.getString("pic_url"));
                }
                home_image.setImageUrl(Config.URL_SERVER + "data/apppic/" + ad.getPic_url(), imageLoader);
                is_getAD = true;
                handler.sendEmptyMessage(LOAD);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 查询获取导航按钮
     */
    class GetNav extends AsyncTask<Void, Void, String> {

        @Override
        protected void onPreExecute() {
            list_nav.clear();
        }

        @Override
        protected String doInBackground(Void... voids) {
            String url = Config.URL_SERVER + "api.php?app_key=" + Config.APP_KEY + "&method=ssy.base.app.nav";
            return OkHttpClientManager.sendGet(url);
        }

        @Override
        protected void onPostExecute(String s) {
            if (s == null) {
                is_getNav = true;
                handler.sendEmptyMessage(LOAD);
                return;
            }
            try {
                JSONObject object = new JSONObject(s);
                if (object.getString("result").equals("success")) {
                    JSONObject object1 = object.getJSONObject("info");
                    JSONArray array = object1.getJSONArray("list");
                    int len = array.length();
                    if (len > 0) {
                        for (int i = 0; i < len; i++) {
                            JSONObject object2 = array.getJSONObject(i);
                            NavigationButton nav = new NavigationButton();
                            nav.setId(object2.getString("id"));
                            nav.setCtype(object2.getString("ctype"));
                            nav.setCid(object2.getString("cid"));
                            nav.setName(object2.getString("name"));
                            nav.setIfshow(object2.getString("ifshow"));
                            nav.setVieworder(object2.getString("vieworder"));
                            nav.setOpennew(object2.getString("opennew"));
                            nav.setUrl(object2.getString("url"));
                            nav.setType(object2.getString("type"));
                            nav.setPic(object2.getString("pic"));
                            list_nav.add(nav);
                        }
                    }
                } else {

                }
                is_getNav = true;
                handler.sendEmptyMessage(LOAD);
                //初始化导航按钮列表
                GridLayoutManager manager = new GridLayoutManager(getActivity(), 5);
                navAdapter = new NavAdapter(getActivity(), R.layout.item_nav_btn, list_nav);
                re_nav.setLayoutManager(manager);
                re_nav.setAdapter(navAdapter);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 导航按钮列表适配器
     */
    class NavAdapter extends CommonAdapter<NavigationButton> {

        public NavAdapter(Context context, int layoutId, List<NavigationButton> datas) {
            super(context, layoutId, datas);
        }

        @Override
        protected void convert(ViewHolder holder, NavigationButton navigationButton, final int position) {
            NetworkImageView image_nav = holder.getConvertView().findViewById(R.id.image_nav);
            image_nav.setImageUrl(Config.URL_SERVER + "data/attached/nav/" + navigationButton.getPic(), imageLoader);
            image_nav.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Toast.makeText(getActivity(), "点击了第" + (position + 1) + "个导航按钮", Toast.LENGTH_SHORT).show();
                }
            });
        }
    }

    /**
     * 商品秒杀列表适配器
     */
    class ReMsAdapter extends CommonAdapter<Goods> {

        public ReMsAdapter(Context context, int layoutId, List<Goods> datas) {
            super(context, layoutId, datas);
        }

        @Override
        protected void convert(ViewHolder holder, final Goods goods, final int position) {
            View view = holder.getConvertView();
            RelativeLayout goods_layout = view.findViewById(R.id.goods_layout);
            NetworkImageView goods_thumb = view.findViewById(R.id.goods_thumb);
            TextView goods_name = view.findViewById(R.id.goods_name);
            TextView goods_shop_price = view.findViewById(R.id.goods_shop_price);
            TextView goods_market_price = view.findViewById(R.id.goods_market_price);
            goods_thumb.setDefaultImageResId(R.mipmap.pic_zwt_2);
            goods_thumb.setErrorImageResId(R.mipmap.pic_zwt_2);
            goods_thumb.setImageUrl(Config.URL_SERVER + goods.getGoods_thumb(), imageLoader);
            goods_name.setText(goods.getGoods_name());
            goods_shop_price.setText("¥ " + goods.getShop_price());
            goods_market_price.setText("¥" + goods.getMarket_price());
            goods_market_price.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);//中间加横线
            goods_layout.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    startActivity(new Intent(getActivity(), GoodsInfoActivity.class).putExtra("goods", goods));
                }
            });
        }
    }

    /**
     * 积分抢购商品列表适配器
     */
    class JfAdapter extends CommonAdapter<Goods> {

        public JfAdapter(Context context, int layoutId, List<Goods> datas) {
            super(context, layoutId, datas);
        }

        @Override
        protected void convert(ViewHolder holder, final Goods goods, final int position) {
            View view = holder.getConvertView();
            LinearLayout goods_layout = view.findViewById(R.id.goods_layout);
            NetworkImageView goods_thumb = view.findViewById(R.id.goods_thumb);
            TextView goods_name = view.findViewById(R.id.goods_name);
            TextView goods_warn = view.findViewById(R.id.goods_warn);//即将售罄
            TextView goods_shop_price = view.findViewById(R.id.goods_shop_price);//¥ 169积分
            TextView goods_market_price = view.findViewById(R.id.goods_market_price);
            TextView btn_buy = view.findViewById(R.id.btn_buy);
            goods_thumb.setDefaultImageResId(R.mipmap.pic_zwt_2);
            goods_thumb.setErrorImageResId(R.mipmap.pic_zwt_2);
            goods_thumb.setImageUrl(Config.URL_SERVER + goods.getGoods_thumb(), imageLoader);
            goods_name.setText(goods.getGoods_name());
            goods_shop_price.setText("¥ " + goods.getShop_price());
            goods_market_price.setText("¥" + goods.getMarket_price());
            goods_market_price.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);//中间加横线
            goods_layout.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    startActivity(new Intent(getActivity(), GoodsInfoActivity.class).putExtra("goods", goods));
                }
            });
            btn_buy.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Toast.makeText(getActivity(), "button点击了" + (position + 1) + "项goods", Toast.LENGTH_SHORT).show();
                }
            });
            if (Integer.parseInt(goods.getGoods_number()) <= Integer.parseInt(goods.getWarn_number())) {
                goods_warn.setVisibility(View.VISIBLE);
            }

        }
    }

    /**
     * 初始化幻灯片
     */
    private void initHDP() {
        viewlist = new ArrayList<View>();
        //设置图片组
        if (list_url != null && list_url.size() > 0) {
            for (int i = 0; i < list_url.size(); i++) {
                imageView = new NetworkImageView(getActivity());
                imageView.setScaleType(ImageView.ScaleType.FIT_XY);
                //设置图片
                imageView.setDefaultImageResId(R.mipmap.pic_zwt_0);
                imageView.setErrorImageResId(R.mipmap.pic_zwt_0);
                imageView.setImageUrl(Config.URL_SERVER + "data/apppic/" + list_url.get(i), imageLoader);
                //设置图片id
                imageView.setId(i);
                viewlist.add(imageView);
            }
        } else {
            ImageView image = new ImageView(getActivity());
            image.setScaleType(ImageView.ScaleType.FIT_XY);
            image.setImageResource(R.mipmap.pic_zwt_0);
            //设置图片id
            image.setId(0);
            viewlist.add(image);
        }
        /*
         * viewpager加载适配器
         * MyPageAdapter为自定义适配器
         *
         */
        //传递上下文
        Context context = getActivity();
        MyPageAdapter pageadapter2 = new MyPageAdapter(viewlist, context);
        viewPager.setAdapter(pageadapter2);
        if (list_url != null && list_url.size() > 0) {
            //点数组
            pointarr = new ImageView[list_url.size()];
            //把点加入布局，和设置点状态
            for (int i = 0; i < list_url.size(); i++) {
                ImageView point = new ImageView(getActivity());

                //设置点大小
                point.setLayoutParams(new ViewGroup.LayoutParams(25, 25));
                pointarr[i] = point;
                //状态处理
                if (i == 0) {
                    pointarr[i].setBackgroundResource(R.mipmap.icon_point_pre);
                } else {
                    pointarr[i].setBackgroundResource(R.mipmap.icon_point);
                }
                //加入到容器
                pointgroup.addView(pointarr[i]);
            }
        } else {
            pointgroup.setVisibility(View.GONE);
        }
        //viewpager设置监听器
        viewPager.setOnPageChangeListener(listener);

        if (flag && list_url != null && list_url.size() > 1) {
            timerTask(); // 定时执行
            flag = false;
        }
    }

    //定时器
    public void timerTask() {
        //创建定时线程执行更新任务
        mTimer.schedule(new TimerTask() {
            @Override
            public void run() {
                count++;
                if (count >= pointarr.length) {
                    count = 0;
                }
                handler.sendEmptyMessage(0x001);
            }
        }, 3000, 3000);// 定时任务
    }

    /**
     * 监听幻灯片
     */
    ViewPager.OnPageChangeListener listener = new ViewPager.OnPageChangeListener() {
        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
        }

        //比如切换到第二张图片，相应索引的点为选择状态，其他为未选中状态
        @Override
        public void onPageSelected(int position) {
            count = position;
            for (int i = 0; i < pointarr.length; i++) {
                pointarr[position].setBackgroundResource(R.mipmap.icon_point_pre);
                if (position != i) {
                    pointarr[i].setBackgroundResource(R.mipmap.icon_point);
                }
            }
        }

        @Override
        public void onPageScrollStateChanged(int state) {
        }
    };


    /**
     * 幻灯片适配器
     */
    public class MyPageAdapter extends PagerAdapter {
        private List<View> viewlist;
        private Context context;

        public MyPageAdapter(List<View> viewlist, Context context) {
            this.viewlist = viewlist;
            this.context = context;
        }

        @Override
        public int getCount() {
            // TODO Auto-generated method stub
            return viewlist.size();
        }

        @Override
        public boolean isViewFromObject(View arg0, Object arg1) {
            // TODO Auto-generated method stub
            return arg0 == arg1;
        }


        //以下也是必要方法，不过要自己添加
        //实例化
        @Override
        public Object instantiateItem(View container, final int position) {
            // TODO Auto-generated method stub
            ((ViewPager) container).addView(viewlist.get(position));
            View view = viewlist.get(position);
            view.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    // TODO Auto-generated method stub
                    int i = v.getId();
                    String t = "你点击了图片的图片id为：" + i + "  图片position为：" + position;
//                    Toast.makeText(context, t, Toast.LENGTH_LONG).show();


                }

            });
            return viewlist.get(position);
        }


        //销毁
        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            // TODO Auto-generated method stub
            container.removeView(viewlist.get(position));
        }

    }


    @Override
    public void onStart() {
        // TODO Auto-generated method stub
        super.onStart();
        // -----------location config ------------
        locationService = ((LocationApplication) getActivity().getApplication()).locationService;
        //获取locationservice实例，建议应用中只初始化1个location实例，然后使用，可以参考其他示例的activity，都是通过此种方式获取locationservice实例的
        locationService.registerListener(mListener);
        //注册监听
        int type = getActivity().getIntent().getIntExtra("from", 0);
        if (type == 0) {
            locationService.setLocationOption(locationService.getDefaultLocationClientOption());
        } else if (type == 1) {
            locationService.setLocationOption(locationService.getOption());
        }

        LocationManager locManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);

        if (!locManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
            // 未打开位置开关，可能导致定位失败或定位不准，提示用户或做相应处理

        }

        //开始定位
        locationService.start();

        //停止定位
//        locationService.stop();

    }

    /***
     * Stop location service
     */
    @Override
    public void onStop() {
        locationService.unregisterListener(mListener); //注销掉监听
        locationService.stop(); //停止定位服务
        super.onStop();
    }

    /*****
     *
     * 定位结果回调，重写onReceiveLocation方法，可以直接拷贝如下代码到自己工程中修改
     *
     */
    private BDAbstractLocationListener mListener = new BDAbstractLocationListener() {

        @Override
        public void onReceiveLocation(BDLocation location) {
            // TODO Auto-generated method stub
            if (null != location && location.getLocType() != BDLocation.TypeServerError) {
                StringBuffer sb = new StringBuffer(256);
                sb.append("time : ");
                /**
                 * 时间也可以使用systemClock.elapsedRealtime()方法 获取的是自从开机以来，每次回调的时间；
                 * location.getTime() 是指服务端出本次结果的时间，如果位置不发生变化，则时间不变
                 */
                sb.append(location.getTime());
                sb.append("\nlocType : ");// 定位类型
                sb.append(location.getLocType());
                sb.append("\nlocType description : ");// *****对应的定位类型说明*****
                sb.append(location.getLocTypeDescription());
                sb.append("\nlatitude : ");// 纬度
                sb.append(location.getLatitude());
                sb.append("\nlontitude : ");// 经度
                sb.append(location.getLongitude());
                sb.append("\nradius : ");// 半径
                sb.append(location.getRadius());
                sb.append("\nCountryCode : ");// 国家码
                sb.append(location.getCountryCode());
                sb.append("\nCountry : ");// 国家名称
                sb.append(location.getCountry());
                sb.append("\ncitycode : ");// 城市编码
                sb.append(location.getCityCode());
                sb.append("\ncity : ");// 城市
                sb.append(location.getCity());
                sb.append("\nDistrict : ");// 区
                sb.append(location.getDistrict());
                sb.append("\nStreet : ");// 街道
                sb.append(location.getStreet());
                sb.append("\naddr : ");// 地址信息
                sb.append(location.getAddrStr());
                sb.append("\nUserIndoorState: ");// *****返回用户室内外判断结果*****
                sb.append(location.getUserIndoorState());
                sb.append("\nDirection(not all devices have value): ");
                sb.append(location.getDirection());// 方向
                sb.append("\nlocationdescribe: ");
                sb.append(location.getLocationDescribe());// 位置语义化信息
                sb.append("\nPoi: ");// POI信息
                if (location.getPoiList() != null && !location.getPoiList().isEmpty()) {
                    for (int i = 0; i < location.getPoiList().size(); i++) {
                        Poi poi = (Poi) location.getPoiList().get(i);
                        sb.append(poi.getName() + ";");
                    }
                }
                if (location.getLocType() == BDLocation.TypeGpsLocation) {// GPS定位结果
                    sb.append("\nspeed : ");
                    sb.append(location.getSpeed());// 速度 单位：km/h
                    sb.append("\nsatellite : ");
                    sb.append(location.getSatelliteNumber());// 卫星数目
                    sb.append("\nheight : ");
                    sb.append(location.getAltitude());// 海拔高度 单位：米
                    sb.append("\ngps status : ");
                    sb.append(location.getGpsAccuracyStatus());// *****gps质量判断*****
                    sb.append("\ndescribe : ");
                    sb.append("gps定位成功");
                } else if (location.getLocType() == BDLocation.TypeNetWorkLocation) {// 网络定位结果
                    // 运营商信息
                    if (location.hasAltitude()) {// *****如果有海拔高度*****
                        sb.append("\nheight : ");
                        sb.append(location.getAltitude());// 单位：米
                    }
                    sb.append("\noperationers : ");// 运营商信息
                    sb.append(location.getOperators());
                    sb.append("\ndescribe : ");
                    sb.append("网络定位成功");
                } else if (location.getLocType() == BDLocation.TypeOffLineLocation) {// 离线定位结果
                    sb.append("\ndescribe : ");
                    sb.append("离线定位成功，离线定位结果也是有效的");
                } else if (location.getLocType() == BDLocation.TypeServerError) {
                    sb.append("\ndescribe : ");
                    sb.append("服务端网络定位失败，可以反馈IMEI号和大体定位时间到loc-bugs@baidu.com，会有人追查原因");
                } else if (location.getLocType() == BDLocation.TypeNetWorkException) {
                    sb.append("\ndescribe : ");
                    sb.append("网络不同导致定位失败，请检查网络是否通畅");
                } else if (location.getLocType() == BDLocation.TypeCriteriaException) {
                    sb.append("\ndescribe : ");
                    sb.append("无法获取有效定位依据导致定位失败，一般是由于手机的原因，处于飞行模式下一般会造成这种结果，可以试着重启手机");
                }

                //logMsg(sb.toString());
                Log.i("定位结果", sb.toString());
            }
        }

    };

}
